<?php
namespace Home\Controller;

use Common\Util\LanzSMSDirectSendSMS;
use Think\Page;

class UserController extends BaseController {
    public function index(){
    	$user = getSessionUser();
    	if (!$user) {
    		$openid = $this->getOpenId();
    		$user = D('User')->getUserByOpenId($openid);
//     		?openid=oqc_3wqCCP5CFoopAoCVEtu45VL8
    		if (!$user || ($user && !$user ['mobile'])) {
    			redirect(U('/User/bind'));
    		} else {
    			$_SESSION ['mdd_user'] = serialize($user);
    		}
    	}
    	
    	$setting = getGlobleConfig();
    	$this->assign('service_hotline', $setting ['service_hotline']);
    	$this->assign('format_service_hotline', format_phone($setting ['service_hotline']));
    	$this->assign('user', $user);
        $this->display();
    }
    
    /**
     * 用户绑定
     */
    public function bind() {
    	unset($_SESSION ['mdd_user']);
    	$user = getSessionUser();
    	if (!$user) {
    		$openid = $this->getOpenId();
    		$user = D('User')->getUserByOpenId($openid);
    		if (!(!$user || ($user && !$user ['mobile']))) {
    			$_SESSION ['mdd_user'] = serialize($user);
    			redirect(U('/User/index'));
    		}
    	} else {
    		redirect(U('/User/index'));
    	}
    	
    	if (!IS_POST) {
    		$redirect = I ('get.redirect');
    		
    		setcookie('openid', '', time() - 1, '/');
    		setcookie('select_province', '', time() - 1, '/');
    		setcookie('select_city', '', time() - 1, '/');
			$this->assign('redirect', $redirect);    		
    		$this->display();
    	} else {
    		$openid = $this->getOpenId();
    		
    		$mobile = I ('post.phone');
    		$code 	= I ('post.code');
    		
    		$verifyMobile = $_SESSION ['mdd_user_phone'];
    		$verifyCode = $_SESSION ['mdd_user_code'];
    		$verifyExpires = $_SESSION ['mdd_code_expires'];
    		 
    		if ($mobile != $verifyMobile || $code != $verifyCode || $verifyExpires < time()) {
    			$this->ajaxReturn(array('status' => 0, 'code' => $verifyCode, 'message' => '验证码无效或已过期'));
    		}
    		
    		$UserModel = D('User');
    		$user = $UserModel->getUserByMobile($mobile, $openid);
    		$wxUser = M('wx_visitor')->where(array('openid' => $openid))->find();
    		
    		$redirect = I('post.redirect');
    		if (!$redirect) {
    			$redirect = U('index');
    		}
    		
    		$UserModel->startTrans();
    		if (!$user) {
    			$select_province = $_COOKIE ['select_province'];
    			$select_city = $_COOKIE ['select_city'];
    			
    			$bindRecord = $UserModel->hasBindRecord($openid);
    			if (!$bindRecord) {
    				$bindData = array(
    						'mobile' => $mobile,
    						'psw'	=> md5($mobile),
    						'username' => $wxUser ['wx_nickname']?$wxUser ['wx_nickname']:'0',
    						'headerimg' => $wxUser ['wx_photo']?$wxUser ['wx_photo']:'0',
    						'select_city'	=> $select_city?$select_city:0,
    						'select_province'	=> $select_province?$select_province:0,
    						'open_id' => $openid,
    						'created'	=> time()
    				);
    				 
    				$id = $UserModel->userBind($bindData);
    				if ($id) {
    					$bindData ['id'] = $id;
    					$_SESSION ['mdd_user'] = serialize($bindData);
    						
    					\Think\Hook::listen('first_bind', $bindData);
    						
    					$relationModel = M('user_weixin_relationship');
    					$data = array(
    						'user_id' => $id,
    						'open_id'=> $openid,
    						'created'=> time()
    					);
    						
    					$relationModel->add($data);
    					
    					$UserModel->commit();
    					$this->ajaxReturn(array('status' => 1, 'redirect' => $redirect));
    				} else {
    					$UserModel->rollback();
    					$this->ajaxReturn(array('status' => 0, 'message' => '绑定失败!1'));
    				}
    			} else {
    				$bindData = array(
    					'mobile' => $mobile,
    					'username' => $wxUser ['wx_nickname']?$wxUser ['wx_nickname']:'0',
    					'headerimg' => $wxUser ['wx_photo']?$wxUser ['wx_photo']:'0',
    					'select_city'	=> $select_city?$select_city:0,
    					'select_province'	=> $select_province?$select_province:0,
    					'open_id' => $openid
    				);
    					
    				$result = $UserModel->where(array('id' => $bindRecord ['id']))->save($bindData);
    				if ($result) {
    					$bindData ['id'] = $bindRecord ['id'];
    					$bindData ['create_time'] = $bindRecord ['create_time'];
    					$user = $bindData;
    				} else {
    					$UserModel->rollback();
    					$this->ajaxReturn(array('status' => 0, 'message' => '绑定失败!4'));
    				}
    			}
    		}
    		
    		$relationModel = M('user_weixin_relationship');
    		$where = array (
    			'user_id' => $user ['id'],
    			'open_id'=> $openid,
    		);
    		
    		$relationRecord = $relationModel->where($where)->find();
    		if (!$relationRecord) {
    			$data = $where;
    			$data ['created'] = time();
    			$result = $relationModel->add($data);
    		} else {
    			if (!$relationRecord ['status']) {
    				$result = $relationModel->where($where)->save(array('status' => 1));
    			} else {
    				$result = true;
    			}
    		}
    		
    		if ($result) {
    			$_SESSION ['mdd_user'] = serialize($user);
    			$UserModel->commit();
    			$this->ajaxReturn(array('status' => 1, 'redirect' => $redirect));
    		} else {
    			$UserModel->rollback();
    			$this->ajaxReturn(array('status' => 0, 'message' => '绑定失败!2'));
    		}
    	}
    }
    
    public function unbind() {
    	$relationModel = M('user_weixin_relationship');
    	$user = $this->getSessionUser();
    	
    	$openid = $this->getOpenId();
    	$where = array(
    		'user_id' => $user ['id'],
    		'open_id'=> $openid,
    	);
    	
    	$result = $relationModel->where($where)->save(array('status' => 0));
    	unset($_SESSION ['mdd_user']);
    	redirect(U('bind'));
        setcookie('openid', '', time() - 1);
    	if ($result) {
    		unset($_SESSION ['mdd_user']);
    		redirect(U('bind'));
    	} else {
    		unset($_SESSION ['mdd_user']);
    		redirect(U('index'));
    	}
    }
    
    /**
     * 检测手机号是否已使用
     * @deprecated
     */
    public function phoneHasBind() {
    	$userModel = D('User');
    	$mobile = I ('get.phone');
    	
    	$exists = $userModel->getUserByMobile($mobile);
    	if ($exists) {
    		$this->ajaxReturn(array('status' => 0));
    	} else {
    		$this->ajaxReturn(array('status' => 1));
    	}
    }
    
    /**
     * 发送手机验证码
     */
    public function sendCode() {
    	$mobile = I ('get.phone');
    	
    	$code = randomPhoneCode(6);
    	$_SESSION ['mdd_user_phone'] = $mobile;
    	$_SESSION ['mdd_user_code'] = $code;
    	$_SESSION ['mdd_code_expires'] = time() + C('SNS_CODE_EXPIRES');
    	
    	$return = array('status' => 0);
    	
    	$LchiObj = new LanzSMSDirectSendSMS();
    	$result = $LchiObj->send($mobile, $code.'(您的美滴滴身份验证码)，有效期为10分钟。如非本人操作，请忽略此短信');
    	$params = array(
    		'mobile' => $mobile,
    		'content' => $code.'(您的美滴滴身份验证码)，有效期为10分钟。如非本人操作，请忽略此短信',
    		'type' => 'user_bind', 
    		'status' => $result?1:0
    	);
    	\Think\hook::listen('message_record', $params);
    	
    	if ($result) {
    		$return ['status'] = 1;
//     		$return ['code'] = $code;
    	}
    	
    	$this->ajaxReturn($return);
    }
    
    public function saveUserCity() {
    	$openid = $this->getOpenid();
    	 
    	$province = I ('get.province');
    	$city = I('get.city');
    	 
    	$cityConfig = array('select_province' => $province, 'select_city' => $city);
    	
    	S('user_select_city_'.$openid, $cityConfig);
    	
    	$UserModel = D('User');
    	$result = $UserModel->updateCitySetting($openid, $cityConfig);
    }
    
    /**
     * 用户优惠券
     */
    public function coupon() {
    	$user = $this->getSessionUser();
    	if (!$user) {
    		redirect(U('bind'));
    	}
    	
    	$userId = getSessionUserId();
    	$UserCouponModel = D('UserCoupon');
    	$expires_time = time();
    	
    	$list = $UserCouponModel->getUserCouponList($userId, $expires_time);
    	$this->assign('coupons', $list);
    	
    	$canNotlist = $UserCouponModel->getUserLostCouponList($userId, $expires_time);
    	$this->assign('notCoupons', $canNotlist);
    	
    	$this->display();
    }
}